<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

      <el-row>
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId" label-width="60">
            <el-select
              v-model="formData.customerId"
              clearable
              filterable
              placeholder="请选择客户"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="24">
          <ContentWrap>
            <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
              <el-tab-pane label="选择产品" name="item">
                <GetProductForm ref="itemFormRef" :items="formData.items"
                />
              </el-tab-pane>
            </el-tabs>
          </ContentWrap>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="图片" prop="remark" label-width="50">
            <UploadImgs :disabled="isDetail" v-model="formData.imgUrl"/>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark" label-width="50">
            <el-input type="textarea" :rows="6" v-model="formData.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>

<!--      <el-button @click="submitForm" type="primary" disabled="false">销售单</el-button>-->
<!--      <el-button @click="submitForm" type="primary" disabled="false">采购单</el-button>-->
<!--      <el-button @click="submitForm" type="primary" disabled="false">派 单</el-button>-->
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {InquiryOrderApi, InquiryOrderVO} from '@/api/erp/inquiryorder'

/** 询价订单 表单 */
defineOptions({name: 'InquiryOrderForm'})
import GetProductForm from "./components/GetProductForm.vue";
import {ref} from "vue";
import {CustomerApi, CustomerVO} from "@/api/erp/sale/customer";

const subTabsName = ref('item')
import {ElMessage, ElLoading} from 'element-plus'

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const customerList = ref<CustomerVO[]>([]) // 客户列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  remark: undefined,
  status: 0,
  orderPrice: undefined,
  items: [],
  imgUrl:undefined,
  sort: 1,
  productList: [],
  productId: undefined,
  customerId: undefined,
})
const formRules = reactive({
  status: [{required: true, message: '开启状态不能为空', trigger: 'blur'}],
  sort: [{required: true, message: '排序不能为空', trigger: 'blur'}],
  customerId: [{required: true, message: '请选择客户信息', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InquiryOrderApi.getInquiryOrder(id)

      formData.value.items = [
        {
          productId: formData.value.productId,
          orderPrice: formData.value.orderPrice,
          productList: formData.value.productList
        }
      ]

    } finally {
      formLoading.value = false
    }
  }
  // 加载客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true;

  try {

    if (formData.value.items.length == 0) {
      ElMessage.error('请选择产品');
      return;
    }
    if (formData.value.items[0].productId == undefined || formData.value.items[0].productId.length == 0) {
      ElMessage.error('请选择产品');
      return;
    }

    formData.value.productId = formData.value.items[0].productId;
    formData.value.orderPrice = formData.value.items[0].orderPrice;

    const data = formData.value as unknown as InquiryOrderVO
    if (formType.value === 'create') {
      await InquiryOrderApi.createInquiryOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await InquiryOrderApi.updateInquiryOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    orderPrice: undefined,
    imgUrl:undefined,
    remark: undefined,
    items: [],
    status: 0,
    sort: 1,
    productList: [],
    productId: undefined,
    customerId: undefined,
  }
  formRef.value?.resetFields()
}
</script>
